package object;

import utils.SHA1;

import java.io.*;
import java.util.ArrayList;


public class Tree extends BaseObject<Tree> implements Serializable{
    protected ArrayList<BaseObject> treeList;       //Objects in Tree

    public Tree(File file) throws Exception{
        this.treeList = new ArrayList<>();
        this.fmt = "Tree";
        this.mode = "040000";
        this.name = file.getName();
        this.path = file.getPath();
        this.key = SHA1.getHash(file);

        buildTreeList(file);

        this.content = genContent();

        writeObject();
    }

    public void buildTreeList(File file) throws Exception{
        File [] fs = file.listFiles();
        for(File f : fs){
            if( f.isFile() ){
                Blob blob = new Blob(f);
                this.treeList.add(blob);
            }
            else if (f.isDirectory()){
                Tree tree = new Tree(f);
                this.treeList.add(tree);
            }
        }
    }

    public String genContent(){
        StringBuilder content = new StringBuilder();
        for(BaseObject g : this.treeList){
            content.append(g.mode).append(" ").append(g.fmt).append(" ").append(g.key).append(" ").append(g.name).append("\n");
        }
        return content.toString();
    }
    @Override
    public void writeObject() {
        try {

            ObjectOutputStream out =
                    new ObjectOutputStream(new FileOutputStream(".jit" + File.separator + "objects" + File.separator + this.key));
            out.writeObject(this);
            out.close();
        }
        catch(Exception ex){
            ex.getStackTrace();
        }

    }

    public static Tree deserialize(String Id) throws Exception {
        try{
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(".jit" + File.separator  + "objects" +File.separator + Id));
            return (Tree) in.readObject();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
